<template>
  <div class="container">
    <div class="navigation width-1000 flex-center">
      <el-form :model="navigationForm" :rules="rules" ref="navigationForm" label-width="100px">
        <el-form-item label="导航地址" prop="navigation_link">
          <el-input v-model="navigationForm.navigation_link"></el-input>
        </el-form-item>
        <el-form-item label="导航名称" prop="navigation_name">
          <el-input v-model="navigationForm.navigation_name"></el-input>
        </el-form-item>
        <el-form-item label="导航LOGO">
          <el-upload
            class="navigation-uploader"
            action=""
            :show-file-list="false"
            :http-request="addnavigationIcon"
            :before-upload="beforeUpload"
          >
            <img
              v-if="navigationForm.navigation_icon"
              :src="navigationForm.navigation_icon"
              width="80px"
              height="60px"
              alt="导航LOGO"
            />
            <i class="iconfont icon-tianjia-daohang" v-if="!navigationForm.navigation_icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="导航类型" prop="navigation_category">
          <el-select v-model="navigationForm.navigation_category.name" placeholder="请选择" size="mini">
            <el-option v-for="item in navigationOptions" :key="item._id" :label="item.name" :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导航介绍" prop="navigation_intro">
          <el-input v-model="navigationForm.navigation_intro"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('navigationForm')">提交</el-button>
          <el-button @click="onCancel">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getNavList, createNavigation, uploadLogo, updateNavigation, getNavigationDetail } from '@/api/navigation'
import { mapGetters } from 'vuex'
export default {
  name: 'NavigationAddEdit',
  props: {
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      navigationForm: {
        navigation_link: '',
        navigation_name: '',
        navigation_icon: '',
        navigation_intro: '',
        navigation_category: ''
      },
      rules: {
        navigation_link: [
          { required: true, message: '请输入导航地址', trigger: 'blur' },
          { validator: this.validatenavigation_link, trigger: 'blur' }
        ],
        navigation_name: [{ required: true, message: '请输入导航名称', trigger: 'blur' }],
        navigation_category: [{ required: true, message: '请选择导航类型', trigger: 'blur' }],
        navigation_intro: [{ required: true, message: '请输入导航介绍', trigger: 'blur' }]
      },
      navigationOptions: [],
      formData: null
    }
  },
  created() {
    this.getUserNavList()
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        if (this.type === 'edit' && !!val) {
          this.getEditData()
        }
      }
    }
  },
  computed: {
    id() {
      return this.$route.params.id
    },
    ...mapGetters(['user_id'])
  },
  methods: {
    // 获取导航类型列表
    async getUserNavList() {
      try {
        const res = await getNavList()
        console.log(res)
        if (res.code === 200) {
          this.navigationOptions = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 提交表单
    onSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const navigationForm = this.navigationForm
          try {
            this.id ? await updateNavigation(this.id, navigationForm) : await createNavigation(navigationForm)
            this.$message({
              type: 'success',
              message: this.id ? '导航修改成功' : '导航添加成功',
              offset: 80
            })
            this.jump()
          } catch (error) {
            console.log('error: ', error)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    onCancel() {
      this.jump()
    },
    async getEditData() {
      try {
        const res = await getNavigationDetail(this.id)
        if (res.code === 200) {
          const { navigation_icon, navigation_intro, navigation_link, navigation_name, navigation_category } = res.data
          this.navigationForm = {
            navigation_link,
            navigation_name,
            navigation_icon,
            navigation_intro,
            navigation_category
          }
        }
      } catch (error) {
        console.log('error: ', error)
      }
    },
    // 上传导航logo
    async addnavigationIcon() {
      const formData = this.formData
      try {
        var result = await uploadLogo(formData)
        this.navigationForm.navigation_icon = result.data.imgUrl
        this.$message({
          type: 'success',
          message: '导航LOGO上传成功',
          offset: 80
        })
      } catch (error) {
        console.log('error: ', error)
      }
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      const typeInfo = ['jpg', 'png', 'jpeg']
      if (!typeInfo.includes(type)) {
        this.$message({
          type: 'error',
          message: '只支持jpg,png,jpeg文件格式！',
          offset: 80
        })
        return false
      }
      if (file.size / 1024 > 2048) {
        this.$message({ type: 'error', message: '图片不能大于2M！' })
        return false
      }
      const formData = new FormData()
      formData.append('files', file)
      this.formData = formData
    },
    // 自定义的校验函数
    validatenavigation_link(rule, value, callback) {
      if (value === '') {
        callback(new Error('导航地址不能为空'))
      } else if (!/^https?:\/\//.test(value)) {
        callback(new Error('导航地址必须包含http://或https://'))
      } else {
        callback()
      }
    },
    // 跳转
    jump() {
      this.$router.replace({ path: '/user/' + this.user_id + '/myNav' })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  .navigation {
    padding: 20px 50px 20px 0;
    background-color: #fff;
    span {
      color: black;
    }
  }
  .el-input {
    width: 500px;
  }
}
</style>
